package com.lyy.mybatis.sensitive.interceptor;


import com.lyy.mybatis.sensitive.utils.EncryptDecryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Lazy;

/**
 * 保存数据加密库拦截器
 *
 * @author lyy 2024/11/23
 */
@Slf4j
@Lazy
@AutoConfiguration
@Intercepts({
        @Signature(method = "update", type = Executor.class, args = {MappedStatement.class, Object.class}),
})
public class SensitiveSaveOrUpdateInterceptor extends SensitiveBaseInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        Object obj = args[1];
        if (!isInsertOrUpdate(mappedStatement)) {
            return invocation.proceed();
        }

        if (EncryptDecryptUtil.checkIsSensitiveTable(obj)) {
            EncryptDecryptUtil.encrypt(obj);
        } else if (obj instanceof MapperMethod.ParamMap) {
            MapperMethod.ParamMap paramMap = (MapperMethod.ParamMap) obj;
            if (paramMap.containsKey("et")) {
                Object paramValue = paramMap.get("et");
                if (EncryptDecryptUtil.checkIsSensitiveTable(paramValue)) {
                    EncryptDecryptUtil.encrypt(paramValue);
                }
            }
        }
        return invocation.proceed();
    }
}
